<?php

function obflush(){
	while(ob_get_level())ob_end_flush();	
	ob_implicit_flush(1);
}


function errorspan($e){
	return '<span class="error">'.$e.'</span>';
}

function changeurlkey($url,$keys){ 
	$url=explode('?',$url);
	if(!isset($url[1]))$url[1]='';
	$url[2]=Array();
	foreach(explode('&',$url[1]) as $av){
		$av=explode('=',$av);
		$url[2][$av[0]]=isset($av[1])?$av[1]:'';		
	};
	foreach($keys as $k=>$v)$url[2][$k]=$v;
	$r=$url[0].'?';
	foreach($url[2] as $k=>$v)$r.=$k.'='.$v.'&';	
	return substr($r,0,-1);	
}



function translate($name){
	$name=(string)$name;
	if(!$name)return NULL;
	static $cache=Array();
	if(isset($cache[$name]))return $cache[$name];
	try{
		$r=$GLOBALS['db']->query('SELECT `value` FROM `dictionary` WHERE `name` LIKE "'.$name.'" AND `lang`="'.UI_LANG.'" LIMIT 1;');
	}catch(Exception $e){
		if($GLOBALS['db']->isTableDoesntExistExeption($e)){			
			$GLOBALS['db']->query('CREATE TABLE IF NOT EXISTS `dictionary` ( `id` int(11) NOT NULL auto_increment, `name` varchar(32) NOT NULL, `value` varchar(255) NOT NULL, `lang` varchar(2) NOT NULL, `verified` tinyint(1) NOT NULL, PRIMARY KEY  (`id`), KEY `name` (`name`) ) ENGINE=MyISAM  DEFAULT CHARSET=utf8');
			obflush();echo "table(dictionary) created";exit;			
		}		
	}
	if($r->num_rows>0){
			$v=str_replace(" "," ",$r->fetch_object()->value);
			$cache[$name]=$v;
			return $v;
	}else {		
		if(FORCEDICTIONARY && strlen($name)<127){
			$GLOBALS['db']->query('INSERT INTO `dictionary` SET `name`="'.$name.'", `lang`="'.UI_LANG.'", `value`="'.$name.'", `verified`=0; ');
		}
		return $name;		
	}
}

function t($n){return translate($n);};

function escape_string($v){
	return $GLOBALS['db']->escape_string($v);	
}


if(!function_exists('com_create_guid')){
	function com_create_guid(){
		mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
		$charid = strtoupper(md5(uniqid(rand(), true)));
		$hyphen = chr(45);// "-"
		$uuid = chr(123)// "{"
				.substr($charid, 0, 8).$hyphen
				.substr($charid, 8, 4).$hyphen
				.substr($charid,12, 4).$hyphen
				.substr($charid,16, 4).$hyphen
				.substr($charid,20,12)
				.chr(125);// "}"
		return $uuid;
	};
};

function loadAjax($url){
	if(!$url)return;
	$id=md5(rand(0,99999));
	echo '<div id="'.$id.'" style="display:inline-block;"></div><script type="text/javascript">$(document).ready(function(){$("#'.$id.'").load("'.$url.'");});</script>';	
}

function loadJS($url){
	if(!$url)return;
	echo '<script type="text/javascript" src="'.$url.'"></script>';	
}


if(!function_exists('removeaccents')){
	setlocale(LC_CTYPE, 'hu_HU.utf8');
	function removeaccents_str($str){		
		$str=str_replace(Array(chr(197),chr(245)),Array('o','u'),$str);
		$str = mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8');
		if(preg_match_all('/&([a-z]*)[a-z]*\;/',$str,$out)){
			foreach($out[1] as $k=>$v)$out[1][$k]=$v[0];
			$str=str_replace($out[0],$out[1],$str);
		};	
		return $str;
	};
	
	function removeaccents(&$arr){
		if(is_string($arr))return removeaccents_str($arr);
		if(is_array($arr))foreach($arr as $k=>$v)$arr[$k]=removeaccents_str($v);
		return $arr;
	}
};


function lowercase($t){
	return $GLOBALS['db']->query("SELECT LOWER('$t') as 'lo';")->fetch_object()->lo;
}

function showimage($n){
	global $controller;
	$n=str_replace('../',$controller->siteroot,$n);	
	ob('<table cellpadding="0" cellspacing="0" border="0" style="margin:-5px;" height="100%"><tbody><tr valign="center"><td valign="center"><br/><br/><br/><br/><br/><br/><img src="'.$n.'" />');
	ob('</td></tr></tbody></table>');	
}

function print_var($obj,$caption=0){
	if(CLI){
		if($caption)echo $caption.": ";var_export($obj,0);echo "\n";
	}else{
		echo '<pre>';
		if($caption)echo "<b>$caption</b>:\n";
		print_r($obj);		
		echo '</pre>';
	}
};	

function console_log($str){
	if(!DEBUG)return;
	if(CLI){
		echo "\n>$str\n";		
	}
	if(is_array($str)){
		$s='Array('."\n";
		foreach($str as $k=>$v){
			$s.=$k.'=>'.$v."\n";
		};
		$s.=");";
		$str=$s;		
	};
	$method=($str[0]=='!'?'warn':'log');
	echo '<script type="text/javascript">if(console && console.'.$method.')console.'.$method.'("';
	echo str_replace("\n",'\n',addslashes($str));
	echo '");</script>'."\n";	
}

function console_error($str){
	if(is_array($str)){
		$s='Array('."\n";
		foreach($str as $k=>$v){
			$s.=$k.'=>'.$v."\n";
		};
		$s.=");";
		$str=$s;		
	}
	echo '<script type="text/javascript">if(console && console.warn)console.warn("';
	echo str_replace("\n",'\n',addslashes($str));
	echo '");</script>'."\n";	
}

function console_info($str){
	if(is_array($str)){
		$s='Array('."\n";
		foreach($str as $k=>$v){
			$s.=$k.'=>'.$v."\n";
		};
		$s.=");";
		$str=$s;		
	}
	echo '<script type="text/javascript">if(console && console.info)console.info("';
	echo str_replace("\n",'\n',addslashes($str));
	echo '");</script>'."\n";	
}

function print_callstack(){
	echo("<pre>");
	debug_print_backtrace();
	echo("</pre>");	
}

function print_struct($t){
	if(!file_exists(DB_STRUCT_CACHE.$t.'.struct'))return 0;
	$s=file_get_contents(DB_STRUCT_CACHE.$t.'.struct');
	$a=unserialize($s);
	print_var($a,'Struct of '.$t);	
}

function collectFrequentItems($in,$n){
	$itms=Array();
	
	foreach($in as $k)if(!isset($itms[$k]))$itms[$k]=0;else $itms[$k]++;
	$max=0;
	foreach($itms as $k)if($max<$k)$max=$k;
	$out=Array();
	$max--;
	while(1){
		foreach($itms as $k=>$v){
			if($v>$max){
				array_push($out,$k);
				unset($itms[$k]);
				if(!count($itms))return $out;
				$n--;				
			};
		};
		$max--;
		if($max<1 || $n<1)return $out;			
	};
};

function HTMLBox(){
	global $controller;
	$controller->requireExternal('jquery','js');
	$controller->requireExternal('htmlbox/htmlbox.colors','js');
	$controller->requireExternal('htmlbox/htmlbox.styles','js');
	$controller->requireExternal('htmlbox/htmlbox.syntax','js');
	$controller->requireExternal('htmlbox/xhtml','js');
	$controller->requireExternal('htmlbox/htmlbox.full','js');
	$o =<<<EOT
<script type='text/javascript'>
var myhtmlbox=0;
$(document).ready(function(){
	myhtmlbox=$('textarea').css("height","100%").css("width","100%").htmlbox({
    toolbars:[
	    [
		// Cut, Copy, Paste
		"separator","cut","copy","paste",
		// Undo, Redo
		"separator","undo","redo",
		// Bold, Italic, Underline, Strikethrough, Sup, Sub
		"separator","bold","italic","underline","strike","sup","sub",
		// Left, Right, Center, Justify
		"separator","justify","left","center","right",
		// Ordered List, Unordered List, Indent, Outdent
		"separator","ol","ul","indent","outdent",
		// Hyperlink, Remove Hyperlink, Image
		"separator","link","unlink","image"		
		],[// Show code
		"separator","code",
        // Formats, Font size, Font family, Font color, Font, Background
        "separator","formats","fontsize","fontfamily",
		"separator","fontcolor","highlight",
		//],[
		//Strip tags
		"separator","removeformat","striptags","hr","paragraph",
		// Styles, Source code syntax buttons
		"separator","quote","styles","syntax"
		]
	],
	skin:"blue"
	});
	$('form').bind('submit',function(){
		myhtmlbox.keyup();//required if no keypress, only d&d to update the content of textarea
	})
});
</script>
EOT;
	return $o;	
}

function TinyMCE($p){
	global $controller;
	$controller->requireExternal('jquery','js');	
	$controller->requireExternal('tinymce/tiny_mce','js');
	$controller->requireExternal('tinymce/jquery.tinymce','js');
	$o =<<<EOT
<script type='text/javascript'>
$(document).ready(function() {
		$('textarea').tinymce({
			// Location of TinyMCE script
			script_url : SITEROOT+'js/tinymce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

			// Theme options
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,

			// Example content CSS (should be your site CSS)
			content_css : SITEROOT+"css/content.css",

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js",

			// Replace values for the template plugin
			template_replace_values : {
				username : "Some User",
				staffid : "991234"
			}
		});
	});

</script>
EOT;
	return $o;	
		
}

function HightlightCurrentMenu(){
	$url=$_SERVER['REQUEST_URI'];
	?>
	<script type="text/javascript" >	
	$('a[href=<?=$url;?>]').each(function(){
		//console.log(this);
		img=0;
		$('img[onmouseover]',this).each(function(){
			img=this;
			hlonFIX(this);
		});
		if(!img){
			$(this).addClass('hover');
		}
	});
	</script>
	<?php 	
}

function SiteRoot2JS(){
	global $controller;
	$o='<script type="text/javascript">var SITEROOT="';
	$o.=$controller->getSiteroot();
	$o.='";var ACTIVEMODULENAME="';
	$o.=Route::$rc['m'];
	$o.='";</script>'."\n";
	return $o;
}

function JQUERYResourceHandler(){
	global $controller;
	$controller->requireExternal('swfobject','js');
	$controller->requireExternal('jquery','js');
	$controller->requireExternal('jquery_contextmenu','js');
	$controller->requireExternal('jquery_uploadify','js');
	$controller->requireExternal('jquery_resourcehandler','js');
	$controller->requireExternal('uploadify','css');	
	$o=<<<EOH
<script type='text/javascript' >
var resourcehandler=0;
$(document).ready(function(){
	resourcehandler=new JQueryResourceHandler('resources');
});
</script>
EOH;
	$o.="\n";
	return $o;	
}

function marqueeinit($p){
	global $controller;
	$controller->requireExternal('marquee','js');
	$controller->requireExternal('jquery','js');
	$controller->requireExternal('marquee','css');
	return '<script type="text/javascript" >$(document).ready(function(){var marquee=new Marquee('.$p.');});</script>'."\n"; 	
}

function pngfix($p){
	global $controller;
	$controller->requireExternal('jquery','js');
	$controller->requireExternal('jquery_pngfix','js');
	return '<script type="text/javascript" >$(document).ready(function(){$(document).pngFix();});</script>'."\n";	
}

function decryptemail(){
	global $controller;
	$controller->requireExternal('email','js');
	return '<script type="text/javascript" >updatemailhref()</script>'."\n";
}

function nospamMail($address){
	$a='';
	for($i=strlen($address)-1;$i>=0;$i--)$a.=$address[$i].chr($i+64);
	$script="a='$a';b='';for(i=a.length-2;i>=0;i-=2)b+=a.charAt(i);";
	echo "<a href='#' onmousedown=\"$script;$(this).attr('href','mailto:'+b);\" ><script type='text/javascript'>$script;document.write(b);</script></a>";
}

function strtodate($v){
	if(!$v)return 0;
	$v=str_replace('.','-',$v);
	if($v[strlen($v)-1]=='-')$v=substr($v,0,-1);
	$d=strtotime($v);
	if(!$d)return 0;
	return date('Y-m-d',$d);
}

function yearsfromnow($v){	
	$now=new DateTime(date('y-m-d'));
	$val=new DateTime($v);
	return $val->diff($now)->format('%y');	
}

function parseDate($v){
	if(strlen($v)>10)$v=substr($v,0,10);
	if(strlen($v)<10)return NULL;
	if(!preg_match('/([0-9]{4})[-|\.]([0-9]{2})[-|.]([0-9]{2})/',$v,$out))return NULL;
	array_shift($out);
	return $out;
}

function parseTime($v){	
	if(strlen($v)>8)$v=substr($v,-8);
	if(!preg_match('/([0-9]{2})[-|:| ]([0-9]{2})[-|:| ]([0-9]{2})/',$v,$out))return NULL;
	array_shift($out);
	return $out;	
}

function strdatetime2timestamp($v){
	$v=(string)$v;
	if($v=='CURRENT_TIMESTAMP' || $v=='now()')$v=Date('Y-m-d H:i:s');
	if($v=='0000-00-00 00:00:00' || $v=='NULL')return 'NULL';
	$d=new DateTime();
	$dt=parseDate($v);
	$ti=parseTime($v);
	$d->setDate($dt[0],$dt[1],$dt[2]);
	$d->setTime($ti[0],$ti[1],$ti[2]);
	$datestring=$dt[0].'-'.$dt[1].'-'.$dt[2].'. '.$ti[0].':'.$ti[1].':'.$ti[2];
	return strtotime($datestring);
}


function isvalidemailaddress($v){
	$regexp = "/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/";
	$v=strtolower($v);
	return preg_match($regexp,$v);	
}

function jsvar($o){
		return 'json_decode(\''.json_encode($o).'\')';
}

function html2pdf($html){
	require_once 'lib/3rdparty/tcpdf/config/lang/eng.php';
	require_once 'lib/3rdparty/tcpdf/tcpdf.php';
	$pdf=new TCPDF(PDF_PAGE_ORIENTATION,PDF_UNIT,'A4',true,'UTF-8',false);/*
	$pdf->SetCreator(PDF_CREATOR);
	$pdf->SetAuthor('Nicola Asuni');
	$pdf->SetTitle('TCPDF Example 061');
	$pdf->SetSubject('TCPDF Tutorial');
	$pdf->SetKeywords('TCPDF, PDF, example, test, guide');/**/
	//$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
	//$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
	
	$pdf->setPrintHeader(false);
	$pdf->setPrintFooter(false);
	$pdf->SetMargins(4,4,4,4);
	
	$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
	
	//set image scale factor
	///$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
	
	//set some language-dependent strings
	$pdf->setLanguageArray($l);
	
	// ---------------------------------------------------------
	// set font
	$pdf->SetFont('courier', '', 10);
	
	// add a page
	$pdf->AddPage();
	$pdf->writeHTML($html, false, false, true, false, '');
	$pdf->lastPage();
	$pdf->output('printtest.pdf','I');
	obflush();
}

function validate_username($name){
	if(strlen($name)<3)return 'username_must_me_at_least_3_character_long'.strlen($name);
	if(strlen($name)>20)return 'username_too_long';
	if($name!=removeaccents($name))return 'disallowed_character';
	global $db;
	$rs=$db->query("SELECT * FROM `user_account` WHERE `name`='".$db->escape_string($name)."';");
	if($rs->num_rows){
		return 'username_already_in_use';
	}
	return NULL;	
}

function validate_password($p1,$p2){
	if($p1!=$p2)return 'password2_differs';
	return NULL;	
}

function validate_email($email){
	if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$email)){
    list($username,$domain)=split('@',$email);
    if(!checkdnsrr($domain,'MX')) {
      return 'emial_provider_cant_be_verified';
    }
    return NULL;
	};
	
	return 'address_format_not_valid';
	
}

function requireIndex($pn,&$p){
	$fs=explode(',',$pn);
	$err=Array();
	foreach($fs as $f){
		if(!isset($p[$f]))$err[$f]='field_must_be_filled';
	}
	return $err;
}

function requireNonNullIndex($pn,&$p){
	$fs=explode(',',$pn);
	$err=Array();
	foreach($fs as $f){
		if(!isset($p[$f]) || !$p[$f])$err['error_'.$f]='field_must_be_filled';
	}
	return $err;
}

function print_cli_2d(&$arr){
	$cws=Array();
	$crows=count($arr);
	for($i=0;$i<$crows;$i++){
		for($j=0;$j<count($arr[$i]);$j++){
			if(!isset($cws[$j]))$cws[$j]=strlen($arr[$i][$j]);
			else{
				$c=strlen($arr[$i][$j]);
				if($c>$cws[$j])$cws[$j]=$c;
			}
		}		
	}
	$sepw=1;foreach($cws as $w)$sepw+=($w+1);
	for($i=0;$i<$sepw;$i++)echo '-';echo "\n";
	for($i=0;$i<$crows;$i++){
		echo '|';
		for($j=0;$j<count($arr[$i]);$j++){
			printf('%'.$cws[$j].'s|',$arr[$i][$j]);
		}
		echo "\n";
		for($j=0;$j<$sepw;$j++)echo '-';echo "\n";
	}
}
/**/
function __autoload($class){
	//console_log('__autoload('.substr($class,0,6).')');
	$class=strtolower($class);
	if( substr($class,-6)=='module')
		$fn=PATH_FFWD.'prototypes/module.'.substr($class,0,-6).'.php';	
	else if(substr($class,-4)=='view')
		$fn=PATH_FFWD.'prototypes/view.'.substr($class,0,-4).'.php';
	else if(substr($class,-5)=='table')
		$fn=PATH_CONFIG.'models/model.'.substr($class,0,-5).'.php';
	else if(substr($class,-4)=='form'){
		$fn=PATH_CONFIG.'forms/form.'.substr($class,0,-4).'.php';		
	}
	else{
		$fn='';
	};
	$fn=strtolower($fn);
	if(file_exists($fn)){
		console_log('autoload: '.$fn);
		require_once($fn);
		return 1;
	};
	eval("class $class{ 
            function __construct() { 
              throw new Exception('Class $class not found');
            }
          
            static function __callstatic(\$m, \$args) {
              throw new Exception('Class $class not found');
            }
          }"); 
}/**/

function js_redirect($url,$justreturnscript=0){
	$s='document.location.assign("'.$url.'")';
	if($justreturnscript)return $s;	
	echo "<script type='text/javascript'>\n$s\n</script>";
}

function js_redirect_timeout($url,$timeout){
	$s=js_redirect($url,1);
	echo "<script type='text/javascript'>";
	echo "setTimeout('$s',$timeout);";
	echo "</script>";
	
}

function js_documentready($code){	
	return "<script type='text/javascript' >$(document).ready(function(){ $code });</script>";
}

function js_validatebyregexp($regexp){
	$s='$(this).attr("regexp","'.$regexp.'");validateinputbyregexpattr(this);';
	return $s;	
}

function js_resourcehandler($p=Array()){
		$GLOBALS['app']->link('jquery','js');
		$GLOBALS['app']->link('jquery_uploadify','js');
		$GLOBALS['app']->link('jquery_contextmenu','js');
		$GLOBALS['app']->link('jquery_resourcehandler','js');
		$GLOBALS['app']->link('uploadify','css');
		if(!isset($p['folder']))$p['folder']='upload';
		$id=substr(md5($p['folder']),0,5);
		
		if(!isset($p['moduleurl']))$p['moduleurl']=substr(link_for('/resource/list'),0,-9);
		$p['user_cookie']=$GLOBALS['user']->getCookieValue();

		
		$p_js=json_encode($p);
		?>
		<div id='uploadify_<?=$id;?>'>[loading]</div>
		<script type='text/javascript'>
			$(document).ready(function(){
				var jrh=new JQueryResourceHandler('#uploadify_<?=$id;?>',<?=$p_js;?>);
			});
		</script>
		<?php
	}

function geterrorstring($code){
	//TODO: implement!
	return $code;	
}


function header_redirect($url,$rc=303){
	if(BLOCKREDIRECT){
		console_log('redirecting to: '.$url);
		throw new Exception('Redirecting blocked');
	}else{
		header('Location: '.$url,$rc);
	}	
}

function is_number($v){		
	return is_numeric($v);
}


function js_jwplayer($target,$videosrc,$p=Array()){
	if(!isset($p['width']))$p['width']=460;
	if(!isset($p['height']))$p['height']=318;
	echo "<script type='text/javascript'>\n";/*
	echo 'var s1 = new swfobject("js/flvplayer.swf","single","'.$p['width'].'","'.$p['height'].'","10");'."\n";
	echo 's1.addParam("allowfullscreen","true");'."\n";
	echo 's1.addParam("allowscriptaccess","always");'."\n";
	echo 's1.addParam("menu","false");'."\n";
	echo 's1.addVariable("file","'.$videosrc.'");'."\n";
	echo 's1.addVariable("skin","Hilltop_player.swf");'."\n";
	echo 's1.addVariable("image","preview.jpg");'."\n";
	echo 's1.addVariable("menu","false");'."\n";
	echo 's1.addVariable("embed","false");'."\n";
	echo 's1.addVariable("width","'.$p['width'].'");'."\n";
	echo 's1.addVariable("height","'.$p['height'].'");'."\n";
	echo 's1.write("'.$target.'");'."\n";/**/
	?>
	swfobject.embedSWF("/js/flvplayer.swf","<?=$target?>", <?=$p['width'];?>, <?=$p['height']; ?>,'9.0.24',null,
	{skin:'/js/Hilltop_player.swf', image:'preview.jpg',file:'<?=$videosrc;?>',embed:false,width:<?=$p['width'];?>, height: <?=$p['height'];?>, allowFullscreen:true},
	{'quality':'high','wmode':'opaque','allowScriptAccess':true,'allowFullscreen':true});
	<?php
	echo "</script>\n";	
}

function file_get_extension($fn){
	$p=strrpos($fn, '.');
	return substr($fn,$p+1);
}

function get_file_icon($type){
		if(file_exists('lib/bi/static/images/icons/'.($type).'.png')){
			return '/images/icons/'.($type).'.png';
		}else{
			return '/images/icons/unknown.png';
		}
	}


function fnwithoutext($fn){	
	$lastdot=strrpos($fn,'.');
	return substr($fn,0,$lastdot);
}

function fnext($fn){	
	$lastdot=strrpos($fn,'.');
	return substr($fn,$lastdot+1);
}

function array2object($array = array()) {
    if (!empty($array)) {
        $data = false;
        foreach ($array as $akey => $aval) {
            $data -> {$akey} = $aval;
        }
        return $data;
    }
    return false;
}

?>
